package com.moli.iov.base.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moli.iov.base.cache.redis.VehicleFenceCacheService;
import com.moli.iov.base.enums.QueryParamEnum;
import com.moli.iov.base.model.VehicleFenceParam;
import com.moli.iov.base.model.dto.req.VehicleFenceReqDto;
import com.moli.iov.base.model.dto.res.VehicleFenceGpsResDto;
import com.moli.iov.base.model.dto.res.VehicleFenceResDto;
import com.moli.iov.base.model.dto.res.VehicleFenceResOpDto;
import com.moli.iov.base.model.po.VehicleFence;
import com.moli.iov.base.service.IVehicleFenceService;
import com.moli.iov.base.util.CollectionUtils;
import com.moli.iov.enums.UserTypeEnum;
import com.moli.iov.model.dto.req.PageExtend;
import com.moli.iov.rest.RestResponse;
import com.moli.iov.base.mapper.VehicleFenceMapper;
import com.moli.iov.util.CommonUtils;
import com.moli.iov.util.JsonUtils;
import com.moli.iov.util.ValidationUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 围栏表  服务实现类
 * </p>
 *
 * @author wanghualin
 * @since 2019-09-03
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class VehicleFenceServiceImpl extends
    ServiceImpl<VehicleFenceMapper, VehicleFence> implements
    IVehicleFenceService {

  @Autowired
  private VehicleFenceCacheService vehicleFenceCacheService;

  @Override
  public RestResponse saveVehicleFence(VehicleFence vehicleFence) {
    ValidationUtils.validateBean(vehicleFence);
    VehicleFenceParam param = new VehicleFenceParam();
    param.queryEqCompanyId(vehicleFence.getCompanyId());
    param.queryEqFenceName(vehicleFence.getFenceName());
    //op不做校验
    if (vehicleFence.getSource() == null) {
      VehicleFence one = getOne(param.get(), false);
      if (one != null) {
        return RestResponse.failure("围栏名称不能相同");
      }
    }
    boolean save = this.save(vehicleFence);
    if (save) {
      vehicleFenceCacheService.setVehicleFence(vehicleFence);
    }
    VehicleFenceResOpDto resOpDto = new VehicleFenceResOpDto();
    resOpDto.setId(vehicleFence.getId());
    return save ? RestResponse.success(resOpDto) : RestResponse.failure("添加失败");
  }

  @Override
  public RestResponse updateVehicleFence(VehicleFence vehicleFence) {
    ValidationUtils.validateBean(vehicleFence);
    //删除缓存在更新
    vehicleFenceCacheService.deleteVehicleFence(vehicleFence.getId());
    boolean save = this.saveOrUpdate(vehicleFence);
    if (save) {
      vehicleFenceCacheService.setVehicleFence(vehicleFence);
    }
    return save ? RestResponse.success() : RestResponse.failure("修改失败");
  }

  @Override
  public RestResponse deleteVehicleFence(VehicleFence vehicleFence) {
    ValidationUtils.validateBean(vehicleFence);
    boolean save = this.saveOrUpdate(vehicleFence);
    if (save) {
      vehicleFenceCacheService.deleteVehicleFence(vehicleFence.getId());
    }
    return save ? RestResponse.success() : RestResponse.failure("删除失败");
  }

  @Override
  public VehicleFence getVehicleFence(Long vehicleFenceId) {
    if (!CollectionUtils.isEmpty(vehicleFenceId)) {
      VehicleFence vehicleFence = vehicleFenceCacheService.getVehicleFenceById(vehicleFenceId);
      if (CollectionUtils.isEmpty(vehicleFence)) {
        VehicleFence byId = this.getById(vehicleFenceId);
        return byId;
      } else {
        return vehicleFence;
      }
    }
    return null;
  }

  @Override
  public RestResponse<PageExtend<VehicleFenceResDto>> listVehicleFence(VehicleFenceReqDto dto) {
    List<VehicleFenceResDto> list = new ArrayList<>();
    VehicleFenceParam param = new VehicleFenceParam();
    if (UserTypeEnum.COMPANY.getFlag() == dto.getSysUserType().intValue()) {
      param.queryEqCompanyId(dto.getSysCompanyId());
    }
    if (dto.getQueryParam() != null && StringUtils.isNotBlank(dto.getQueryValue())) {
      if (QueryParamEnum.FENCE_AREA.getCode() == dto.getQueryParam()) {
        param.queryLikeFenceArea(dto.getQueryValue());
      }
      if (QueryParamEnum.FENCE_NAME.getCode() == dto.getQueryParam()) {
        param.queryLikeFenceName(dto.getQueryValue());
      }
    }
    List<VehicleFence> vehicleFenceList = list(param.get());
    PageExtend<VehicleFenceResDto> res = new PageExtend<>();
    if (!CollectionUtils.isEmpty(vehicleFenceList)) {
      for (VehicleFence record : vehicleFenceList) {
        VehicleFenceResDto vehicleFenceResDto = new VehicleFenceResDto();
        CommonUtils.copyProperties(record, vehicleFenceResDto);
        vehicleFenceResDto
            .setFenceAreaCoordinateList(JsonUtils.parse(record.getFenceAreaCoordinate(),
                VehicleFenceGpsResDto.class));
        vehicleFenceResDto
            .setFenceAreaCoordinateRangeList(JSON.parseArray(record.getFenceAreaCoordinateRange(),
                VehicleFenceGpsResDto.class));
        list.add(vehicleFenceResDto);
      }
      res.setRecords(list);
    }
    res.setPageSize(dto.getPageSize());
    res.setTotal((long) list.size());
    res.setPageNumber(dto.getPageNum());
    return RestResponse.success(res);
  }



  @Override
  public List<VehicleFence> listVehicleFenceByIds(Set<Long> fenceIds) {
    if (!CollectionUtils.isEmpty(fenceIds)) {
      List<VehicleFence> vehicleFences = listVehicleFence();
      return CollectionUtils.isEmpty(vehicleFences) ? null : vehicleFences.stream()
          .filter(vehicleFence -> fenceIds.contains(vehicleFence.getId())).collect(
              Collectors.toList());
    }
    return new ArrayList<>();
  }

  @Override
  public List<VehicleFence> listVehicleFence() {
    Map<String, String> fencesMap = vehicleFenceCacheService.listVehicleFencesMap();
    if (CollectionUtils.isEmpty(fencesMap)) {
      VehicleFenceParam param = new VehicleFenceParam();
      List<VehicleFence> list = list(param.get());
      if (!CollectionUtils.isEmpty(list)) {
        vehicleFenceCacheService.setVehicleFence(list);
        return list;
      }
    } else {
      List<VehicleFence> vehicleFence = new ArrayList<>();
      for (Entry<String, String> entry : fencesMap.entrySet()) {
        vehicleFence.add(JsonUtils.parse(entry.getValue(), VehicleFence.class));
      }
      return vehicleFence;
    }
    return new ArrayList<>();
  }

  @Override
  public List<VehicleFence> listVehicleFences() {
    VehicleFenceParam param = new VehicleFenceParam();
    return list(param.get());
  }

  @Override
  public void initVehicleFence() {
    //清空缓存
    vehicleFenceCacheService.cleanVehicleFenceCache();
    VehicleFenceParam param = new VehicleFenceParam();
    List<VehicleFence> list = list(param.get());
    if (!CollectionUtils.isEmpty(list)) {
      vehicleFenceCacheService.setVehicleFence(list);
    }
  }

  @Override
  public List<VehicleFence> listVehicleFenceByOpIds(List<Long> fenceIds, Long companyId) {
    VehicleFenceParam param = new VehicleFenceParam();

    param.queryEqCompanyId(companyId);
    param.queryInFenceIds(fenceIds);
    return list(param.get());
  }


}
